
//
//  NEBaseTeamHistoryFileMessageController.swift
//  NETeamUIKit
//
//  Created by Laura on 2024/7/30.
//

import NECommonKit
import NIMSDK
import UIKit

private let cellId = "cellId"
private let headId = "headId"

@objcMembers
open class NEBaseTeamHistoryImageMessageController: NEBaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    public let viewModel = TeamHistoryMessageViewModel()

    /// 群id
    public var teamId: String?
    var tag = "TeamHistoryImageMessageController"
    
    /// 历史消息列表
    public lazy var collectionView: UICollectionView = {
      let flowLayout = UICollectionViewFlowLayout()
      flowLayout.scrollDirection = .vertical
      flowLayout.minimumLineSpacing = 1
      flowLayout.minimumInteritemSpacing = 0
      flowLayout.estimatedItemSize = CGSize(width: (UIScreen.main.bounds.size.width - 33) / 4, height: (UIScreen.main.bounds.size.width - 33) / 4)
    
      let collectionView = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: flowLayout)
      collectionView.translatesAutoresizingMaskIntoConstraints = false
      collectionView.delegate = self
      collectionView.dataSource = self
      collectionView.backgroundColor = .clear
      collectionView.showsHorizontalScrollIndicator = false
      collectionView.showsVerticalScrollIndicator = false
//      collectionView.isScrollEnabled = false
      collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
      collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headId)
      return collectionView
    }()
    
    /// 空占位图
    public lazy var emptyView: NEEmptyDataView = {
      let view = NEEmptyDataView(
        imageName: "emptyView",
        content: localizable("no_search_results"),
        frame: CGRect.zero
      )
      view.translatesAutoresizingMaskIntoConstraints = false
      view.isUserInteractionEnabled = false
      view.isHidden = true
      return view

    }()
    
    public init(teamId: String?) {
        super.init(nibName: nil, bundle: nil)
        self.teamId = teamId
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override open func viewDidLoad() {
        super.viewDidLoad()
        weak var weakSelf = self

        viewModel.getTeamInfo(teamId) { team, error in
            if team?.isValidTeam == false || team == nil {
                weakSelf?.view.makeToast(localizable("team_not_exist"))
            }
        }
        setupSubviews()
        initialConfig()
  }

    open func setupSubviews() {
      
        view.addSubview(collectionView)
        view.addSubview(emptyView)

        emptyView.isHidden = true

        NSLayoutConstraint.activate([
            emptyView.rightAnchor.constraint(equalTo: collectionView.rightAnchor),
            emptyView.leftAnchor.constraint(equalTo: collectionView.leftAnchor),
            emptyView.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor),
            emptyView.topAnchor.constraint(equalTo: collectionView.topAnchor),
        ])
    }

    open func initialConfig() {
        title = localizable("historical_record_image_video")
        navigationView.moreButton.isHidden = true
        
        toSearchHistory()
    }

    /// 搜索历史消息
    func toSearchHistory() {
        viewModel.searchResultInfos?.removeAll()
        collectionView.reloadData()
      
        guard let teamId = teamId else {
            return
        }
        weak var weakSelf = self
        weakSelf?.viewModel.searchHistoryImageMessages(teamId) { error, messages in
            NEALog.infoLog(
                ModuleName + " " + self.tag,
                desc: "CALLBACK searchHistoryImageMessages " + (error?.localizedDescription ?? "no error")
            )
            if error == nil {
                if let msg = messages, msg.count > 0 {
                    weakSelf?.emptyView.isHidden = true
                } else {
                    weakSelf?.emptyView.isHidden = false
                }
                weakSelf?.collectionView.reloadData()
            } else {
                NEALog.errorLog(
                    ModuleName + " " + (weakSelf?.tag ?? "TeamHistoryMessageController"),
                    desc: "searchMessages failed, error = \(error!)"
                )
            }
        }
    }
    
    // MARK: UICollectionViewDataSource
    open func numberOfSections(in collectionView: UICollectionView) -> Int {
        // 分组的数量
        return viewModel.searchImageResultInfoKeys.count
    }
     
    open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 每组的项目数量
        return viewModel.searchImageResultInfos[viewModel.searchImageResultInfoKeys[section]]?.count ?? 0
    }
     
    
    open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        return cell
    }
    
    open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headId, for: indexPath)
            headerView.backgroundColor = .orange
            return headerView
        }
        return UICollectionReusableView()
    }
    
    // MARK: UICollectionViewDelegateFlowLayout
    open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if viewModel.searchImageResultInfos[viewModel.searchImageResultInfoKeys[section]]?.count ?? 0 == 1 {
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: collectionView.frame.size.width - (UIScreen.main.bounds.size.width - 33) / 4)
        }
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
        return CGSize(width: UIScreen.main.bounds.size.width, height: 46)
    }

    open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (UIScreen.main.bounds.size.width - 33) / 4, height: (UIScreen.main.bounds.size.width - 33) / 4)
    }
    
    // MARK: UICollectionViewDelegate
    open func collectionView(_ collectionView: UICollectionView,
                             didSelectItemAt indexPath: IndexPath) {
        
        let messages = viewModel.searchImageResultInfos[viewModel.searchImageResultInfoKeys[indexPath.section]] ?? []
                    
        let rawAttachContent = messages[indexPath.row].rawAttachContent ?? ""
        
        print(rawAttachContent)
        if let messageContent = jsonStringToDictionary(jsonString: rawAttachContent), let url = messageContent["url"] as? String {
            
            if messages[indexPath.row].messageType == NIMMessageType.video  {
                toVideoView(url, duration: messageContent["dur"] as? Int)
            } else {
                toImageView(url)
            }
        }
    }
    
    public func jsonStringToDictionary(jsonString: String) -> [String: Any]? {
        guard let jsonData = jsonString.data(using: .utf8) else { return nil }
        
        do {
            let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]
            return jsonDict
        } catch {
            print("Error parsing JSON: \(error)")
            return nil
        }
    }
    
    /// 跳转视图显示控件
    /// - Parameter model: 标记对象
    open func toImageView(_ url: String?) {
      if let imageUrlString = url {
        if imageUrlString.count > 0 {
          let showController = PhotoBrowserController(urls: [imageUrlString], url: imageUrlString)
          showController.modalPresentationStyle = .overFullScreen
          present(showController, animated: false, completion: nil)
        }
      }
    }

    /// 跳转视频播放器
    /// - Parameter model: 标记对象
    public func toVideoView(_ url: String?, duration: Int?) {
      if let videoUrl = url {
        let player = VideoPlayerViewController()
        player.totalTime = duration ?? 0
        player.modalPresentationStyle = .overFullScreen
        player.videoUrl = URL(string: videoUrl)
        present(player, animated: true, completion: nil)
      }
    }
}
